package chapter12.section4;
/*程序12-6b：基于对象传输的客户端程序*/
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class EBankClient3 {
	public static void main(String[] args) {
		String[] types={"deposit","withdraw","query","bye"};
		Socket client=null;
		try {
			client=new Socket("127.0.0.1",7788);
			ObjectInputStream in=null;
			ObjectOutputStream out=null;
              //构建基于对象的输入流和输出流
			out = new ObjectOutputStream(client.getOutputStream());
			in = new ObjectInputStream(client.getInputStream());
			Transaction tran=null;
			String resp=null;
			Scanner sc=new Scanner(System.in);
			boolean working=true;
			while(working){
				System.out.println("输入您的账户id：");
				String id=sc.next();
				System.out.println(
"选择本次业务类型[0:存款,1:取款,2：查询,3：退出]：");
				int type=sc.nextInt();
				int amount=0;
				if(types[type].equals("bye")){
					working=false;
					tran=new Transaction(types[type],null,0);
				}else{
					if(types[type].equals("deposit")
||types[type].equals("withdraw")){
						System.out.println("输入交易金额：");
						amount=sc.nextInt();
					}else{
						amount=0;
					}
                       //构建本次发送的业务实例
					tran=new Transaction(types[type],id,amount);
				}
				//将请求信息提交到服务器
				out.writeObject(tran);
				out.flush();//因为对象传输没有自动提交设置，需主动提交
				if(working){
					//接受服务器的响应
					resp=(String)in.readObject();
					System.out.println("response:"+resp);				
				}
			}
			client.close();
		} catch (UnknownHostException e) {
			System.out.println("指定的服务器地址错误");
			System.exit(-1);
		} catch (IOException e) {
			System.out.println("创建和服务器的连接时发生错误");
			System.exit(-1);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
}